package cn.xorange.commons.data.handler;

import cn.xorange.commons.data.annotation.MTable;
import cn.xorange.commons.data.configuration.GlobalDataConfig;
import cn.xorange.commons.data.constants.FieldConstants;
import cn.xorange.commons.data.core.entity.TreeEntity;
import cn.xorange.commons.data.mapper.DaoHelperMapper;
import cn.xorange.commons.datasource.configuration.MyBatisProperties;
import cn.xorange.commons.datasource.configuration.MyTableInfoHelper;
import cn.xorange.commons.exception.DataException;
import cn.xorange.commons.utils.lang.ObjectUtils;
import cn.xorange.commons.utils.spring.SpringUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author : yangjian
 * date : 2024/12/20
 * description :
 */
@Component
public class MyBatisPlusDataFillHandle implements MetaObjectHandler {

    IFillData fillData = SpringUtils.getBean("cn.xorange.commons.core.handler.FillDataImpl");

    @Override
    public void insertFill(MetaObject metaObject) {

        boolean isTree = metaObject.hasGetter(FieldConstants.IS_TREE);
        if(isTree){
            Long parentId = ObjectUtils.toLong(metaObject.getValue(FieldConstants.PARENT_ID));
            if(parentId == 0L){
                setFieldValByName(FieldConstants.PARENT_ID, 0L, metaObject);
                setFieldValByName(FieldConstants.TREE_NODE, "0", metaObject);
            }else {
                boolean mapUnderscoreToCamelCase = SpringUtils.getBean(MyBatisProperties.class).mapUnderscoreToCamelCase;
                Class<?> aClass = metaObject.getOriginalObject().getClass();
                String keyCol = MyTableInfoHelper.getKeyFieldName(aClass,mapUnderscoreToCamelCase);
                String tableName = MyTableInfoHelper.initTableNameByMTable(aClass,mapUnderscoreToCamelCase);
                TreeEntity parentEnt = SpringUtils.getBean(DaoHelperMapper.class).getTreeById(tableName,keyCol,parentId);
                setFieldValByName(FieldConstants.TREE_NODE, parentEnt.getTreeNode()+","+parentId , metaObject);
            }
        }
        setFieldValByName(FieldConstants.TENANT_ID, fillData.tenantId(), metaObject);
        setFieldValByName(FieldConstants.CREATE_TIME, new Date(), metaObject);
        setFieldValByName(FieldConstants.CREATE_BY_ID, fillData.userId(), metaObject);
        setFieldValByName(FieldConstants.CREATE_BY, fillData.userName(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName(FieldConstants.UPDATE_BY_ID, fillData.userId(), metaObject);
        setFieldValByName(FieldConstants.UPDATE_BY, fillData.userName(), metaObject);
        setFieldValByName(FieldConstants.UPDATE_TIME, new Date(), metaObject);
    }
}
